param(
    [Parameter(Mandatory=$True)]
    [object]$vdi_list,
    [Parameter(Mandatory=$false)]
    [string]$execution_file="C:\Users\#fid\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\runClientLogin.lnk"
)
Try{
    $this_path = Split-Path -Parent ($MyInvocation.MyCommand.Definition) -ea 1       # this script running directory
}Catch{
    $FullPathToEXE = [System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName
    $this_path = [System.IO.Path]::GetDirectoryName($FullPathToEXE)                  # for later complied to exe running use
}Finally{}
$this_user=$env:username
$this_machine=$env:computername
$log_file="$this_path\executin_out.log"
clear-content $log_file -force -ea 0 
"{0}--{1:}----------------------------START OF SCRIPT----------------------------" -f (get-date).tostring("yyyy-MM-dd HH:mm:ss"),"Normal"| Out-File -FilePath $log_file -Append -Encoding utf8 -Force
$trigger_action={
    param($line,$cnt,$trigger_params)
    Function Write-Log(){
        param(
            [Parameter(Mandatory=$true)]
            [ValidateSet("Warning", "Error", "Success","Normal")]
            $log_type,
            $log_info,
            $log_file
        )
        $cnt=0
        Do{
            Try{(get-date).tostring("yyyy-MM-dd HH:mm:ss")+"--"+$log_type+": "+$log_info |Out-File -FilePath $log_file -Append -Encoding utf8 -Force ;$rst=$true}Catch{$rst=$false
            sleep 1 ;$cnt++; if($cnt -gt 5){write-error "wait too long(5s) to write log";return}
            }Finally{}
        }While( !$rst )
    }
    Try{$vdi,$fid=$line.split(",")}Catch{}Finally{}
    if($fid -like "*\*"){$rfid=$fid.split('\')[1]}
    Try{$execution_file,$log_file=$trigger_params}Catch{}Finally{}
    # MSG $rfid /SERVER:$vdi /TIME:10 /V /W "AA client will be started in 10s, please do not take any action during this process."
    write-host "Starting to run |$execution_file| in |$cnt-$vdi| in |$fid| session"
    $execution_file=$execution_file.replace("#fid",$rfid)
    If(Test-Connection $vdi -quiet -count 1 -ErrorAction Ignore){
        Get-Service RemoteRegistry -cn $vdi|?{$_.Status -ieq "Stopped"}|Start-Service # so that we can run reg command on remote vdi
        $loop_cnt=0
        Do{
            $rst= (Get-Service RemoteRegistry -cn $vdi).Status
            sleep -Milliseconds 500; $loop_cnt++
            If( $loop_cnt -gt 19 ){
                write-log Error "RemoteRegistry service still not running after 10s in $vdi" $log_file
            }
        }While( $rst -ine "running" )
        # #<--------------------------------------------------- edit reg so that it's allowed to run quser in remote vdi
        reg add "\\$vdi\HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v AllowRemoteRPC /t Reg_Dword /d 0x1 /f 1>$null 2>&1
        If( quser $rfid /server:$vdi 2>$null){
            If(![string]::IsNullOrWhiteSpace( $execution_file) ){
                $remote_execution_file="\\$vdi\"+$execution_file.replace(":",'$')
                If( $execution_file -imatch "lnk$"){
                    $Shell = New-Object -ComObject WScript.Shell 
                    $execution_file=$Shell.CreateShortcut($remote_execution_file).TargetPath
                }
                If( test-path $remote_execution_file -ea 0){
                     SCHTASKS /CREATE /S $vdi /RU $fid /tn ExecutonFileTrigger /sc ONCE  /st (get-date).tostring("HH:mm") /F `
                     /tr $execution_file 1>$null 2>&1
                     If( SCHTASKS /QUERY /S $vdi /tn ExecutonFileTrigger 2>$null){
                         SCHTASKS /RUN /S $vdi /tn ExecutonFileTrigger 1>$null 2>&1
                         write-host "End of running Task ExecutonFileTrigger in |$cnt-$vdi| in |$fid| session`n"
                         write-log Success "Task ExecutonFileTrigger has been created and ran in $vdi with param $execution_file" $log_file
                     }
                }
            }else{write-log Error "execution_file is either null or empty" $log_file}
        }else{write-log Error "$cnt-not found fid $fid logged in vdi $vdi/or access denied to check user login status in $vdi" $log_file}
    }else{write-log Error "$cnt-vdi $vdi is either offline or not a valid vdi name" $log_file}
}
If( [string]::IsNullOrWhiteSpace($vdi_list ) ){
    "vdi_list is either null or empty"| Out-File -FilePath $log_file -Append -Encoding utf8 -Force
    "{0}--{1:}----------------------------END OF SCRIPT------------------------------" -f (get-date).tostring("yyyy-MM-dd HH:mm:ss"),"Normal"| Out-File -FilePath $log_file -Append -Encoding utf8 -Force
    Exit
}
Start-BulkThreads ($vdi_list.split("`n")|?{![string]::IsNullOrWhiteSpace($_.trim())}) $trigger_action $execution_file,$log_file
"{0}--{1:}----------------------------END OF SCRIPT------------------------------" -f (get-date).tostring("yyyy-MM-dd HH:mm:ss"),"Normal"| Out-File -FilePath $log_file -Append -Encoding utf8 -Force
